<template>
    <div>
        <el-page-header @back="$router.push(`/home/index`)" content="个人信息">
        </el-page-header>
        <el-divider></el-divider>

        <!-- 修改信息 -->
        <el-form label-width="100px" style="max-width: 300px;" ref="userForm" :model="userForm">
            <el-form-item>
                <template #label>
                    <h2 style="color:black">修改信息</h2>
                </template>
            </el-form-item>

            <el-form-item label="头像">
                <!-- action:相当于上传路径 -->
                <el-upload :action="upload.url" :headers="upload.headers" :auto-upload="false"
                    :file-list="upload.fileList" :on-change="handleChange" :show-file-list="false" ref="uploadRef">
                    <el-avatar :size="100">
                        <img v-if="upload.previewList" :src="upload.previewList" alt="">
                        <img v-if="upload.previewList == undefined" :src="'/student/v3' + userForm.avatar" alt="">
                    </el-avatar>
                </el-upload>

            </el-form-item>

            <el-form-item label="账号" prop="userName">
                <el-input v-model="userForm.userName" disabled></el-input>
            </el-form-item>

            <el-form-item label="姓名" prop="realName">
                <el-input v-model="userForm.realName"></el-input>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="handleSure">提交</el-button>
                <el-button type="info" @click="resetForm('userForm')">重置</el-button>
            </el-form-item>
        </el-form>

        <el-divider></el-divider>

        <!-- 修改密码 -->
        <el-form ref="passwordForm" :model="passwordForm" :rules="passwordRules" label-width="100px" style="max-width: 300px;">
            <el-form-item label="原密码" prop="originalPassword" >
                <el-input type="password" v-model="passwordForm.originalPassword"></el-input>
            </el-form-item>
            <el-form-item label="新密码" prop="password">
                <el-input type="password" v-model="passwordForm.password"></el-input>
            </el-form-item>
             <el-form-item label="确认密码" prop="confirmPassword">
                <el-input type="password" v-model="passwordForm.confirmPassword"></el-input>
            </el-form-item>
            <el-form-item>
                <el-button type="primary" @click="submitForm">提交</el-button>
                <el-button @click="resetPasswordForm">重置</el-button>
            </el-form-item>
        </el-form>

    </div>

</template>

<script>
import { updateUserInfo, updatePwd } from '@/api/user.js'
import { getToken } from '@/utils/cookie.js'
export default {
    name: "Info",
    data() {
        const validateConfirmPassword = (rule, value, callback) => {
            if (!value) {
                return callback(new Error('请输入确认密码'));
            }
            if (value!== this.passwordForm.password) {
                return callback(new Error('两次输入的密码不一致'));
            }
            callback();
        };


        return {
            //赋值用户信息
            userForm: {
                userId: 700,
                userName: undefined,
                avatar: undefined,
                realName: undefined,
            },

            initialAvatar: null,
            //上传
            upload: {
                url: "/student/v3/prod-api/file/upload",
                headers: {
                    Authorization: `Bearer ${getToken()}`,
                },
                fileList: [],//接收已经上传或选择的图片信息
                previewList: undefined,//临时链接，用来存储预览的照片
            },

            passwordForm: {
                userId: null, 
                originalPassword: '',
                password: '',
                confirmPassword: '' // 新增确认密码字段
              
            },

            passwordRules: {
               originalPassword: [
                    { required: true, message: '请输入原密码', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入新密码', trigger: 'blur' },
                    { min: 6, message: '密码长度至少为6位', trigger: 'blur' }
                ],
                confirmPassword: [
                    { required: true, validator: validateConfirmPassword, trigger: 'blur' }
                ]
            }

        }
    },
    //深度监听
    watch: {
        "$store.state.userInfo": {
            immediate: true,
            deep: true,
            handler(newVal) {
                if (newVal) {
                    const { userId, userName, avatar, realName } = JSON.parse(JSON.stringify(newVal))
                    this.userForm = { userId, userName, avatar, realName }

                    //保存初始头像
                    this.initialAvatar = avatar
                    this.passwordForm.userId = userId; // 同步 userId 到密码表单
                }
            }
        },

    },
    created() {

    },

    methods: {
        //图片上传,手动给fileList赋值
        handleChange(file, fileList) {
            console.log(file);
            console.log(fileList);

            //准备状态时，才控制图片
            if (file.status === "ready") {
                //改头像，以最后一次选择为主
                this.upload.fileList = [file]

                //清空旧头像的预览缓存
                URL.revokeObjectURL(this.upload.previewList)

                //实现头像预览=>临时链接
                this.upload.previewList = URL.createObjectURL(file.raw)

            }

            //头像上传成功
            if (file.status === "success") {
                const { code, data } = file.response

                //获取头像的最新链接
                if (code === 200) {
                    this.userForm.avatar = data.fileUrl

                    //获取头像后，就可以清空头像缓存文件和头像预览链接
                    this.upload.fileList = []
                    this.upload.previewList = undefined
                    this.handleSure()
                }
            }


        },
        //点击确定提交修改用户信息
        handleSure() {
            //先手动上传图片
            if (this.upload.fileList.length > 0) {
                this.$refs[`uploadRef`].submit()
                return
            }

            //若没有文件上传或文件已上传完毕，成功修改用户信息
            updateUserInfo(this.userForm).then(res => {
                this.$message.success(res.msg)
                //重新获取个人信息
                this.$store.dispatch("getUserInfo")
            })
        },

        //重置时，头像恢复为初始值
        resetForm() {
            this.$refs[`uploadRef`].resetFields()
            //将头像恢复为初始值
            this.userForm.avatar = this.initialAvatar
            //清空临时数据
            this.upload.fileList = [],
            this.upload.previewList = undefined
            this.resetPasswordForm()
        },

          resetPasswordForm() {
            this.$refs.passwordForm.resetFields();
        },

        //提交前检验两次密码是否一致
        submitForm() {
            this.$refs.passwordForm.validate(async (valid) => {
                if (valid) {
                    try {
                        // 提交前移除confirmPassword字段（后端不需要）
                        const { confirmPassword, ...submitData } = this.passwordForm;
                        const response = await updatePwd(submitData);
                        
                        if (response.data) {
                            if (response.data.msg === '修改密码成功') {
                                this.$message.success('密码修改成功');
                                this.resetPasswordForm();
                            } else {
                                this.$message.error(response.data.msg || '密码修改失败');
                            }
                        } else {
                            this.$message.success('密码修改成功');
                            this.resetPasswordForm();
                        }
                    } catch (error) {
                        if (error.response && error.response.status === 422) {
                            const errorMessage = error.response.data?.errors?.[0] || '输入的数据不符合要求，请检查后重试';
                            this.$message.error(errorMessage);
                        } else {
                            console.error('请求错误：', error);
                            this.$message.error('网络异常，请稍后再试');
                        }
                    }
                }
            });
        },
       
    },
}


</script>

<style lang="scss" scoped></style>